package edu.pku.sei.transformation.editor.views.problem;

import java.util.List;

import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.ui.IPageLayout;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

import edu.pku.sei.modeler.model.core.MetaModel;
import edu.pku.sei.modeler.project.AbstractModelingProject;
import edu.pku.sei.modeler.project.ProjectRegistry;

public class ProblemView {
	public static final String CODEGEN_ATL = "edu.pku.sei.transformation.codegen.atl";
	public static final String CODEGEN_QVT = "edu.pku.sei.transformation.codegen.qvt";
	public static final String CODEGEN = "edu.pku.sei.transformation.codegen";
	public static final String EXECUTION = "edu.pku.sei.transformation.execution";

	public static void showView() {
		IWorkbench wb = PlatformUI.getWorkbench();
		IWorkbenchWindow window = wb.getActiveWorkbenchWindow();
		IWorkbenchPage page = window.getActivePage();
		try {
			page.showView(IPageLayout.ID_PROBLEM_VIEW);
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}

	public static IProject findProject(MetaModel model) {
		IProject proj = null;
		List projs = ProjectRegistry.getDefault().getProjects();
		for (int i = 0; i < projs.size(); i++) {
			AbstractModelingProject ap = (AbstractModelingProject) projs.get(i);
			if (ap.getModel() == model) {
				proj = ap.getProject();
				break;
			}
		}
		return proj;
	}

	public static void clearMarks(MetaModel model) {
		IProject proj = findProject(model);
		if (proj != null) {
			try {
				proj.deleteMarkers(IMarker.PROBLEM, true, 3);
			} catch (CoreException e) {
				e.printStackTrace();
			}
		}
	}

	public static void addError(MetaModel model, String type, String name,
			String description, String source) {
		IProject proj = findProject(model);
		if (proj != null) {
			try {
				IMarker marker = proj.createMarker(type);
				marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_ERROR);
				marker.setAttribute(IMarker.MESSAGE, description);
				marker.setAttribute(IMarker.PROBLEM, name);
				marker.setAttribute(IMarker.LOCATION, source);
			} catch (CoreException e) {
				e.printStackTrace();
			}
		}
	}

	public static void addWarning(MetaModel model, String type, String name,
			String description, String source) {
		IProject proj = findProject(model);
		if (proj != null) {
			try {
				IMarker marker = proj.createMarker(type);
				marker.setAttribute(IMarker.SEVERITY, IMarker.SEVERITY_WARNING);
				marker.setAttribute(IMarker.MESSAGE, description);
				marker.setAttribute(IMarker.PROBLEM, name);
				marker.setAttribute(IMarker.LOCATION, source);
			} catch (CoreException e) {
				e.printStackTrace();
			}
		}
	}
}
